import * as Lodash from 'lodash';
import { GenTableColumnEntity } from '../../entities/gen-table-cloumn.entity';

// 字典获取脚本模板
export const indexScriptDict = (columns: GenTableColumnEntity[]) => {
  let script = '';
  const dict = [];
  columns.forEach((item) => {
    if (item.dictType != '') {
      dict.push(item.dictType);
    }
  });
  const noRepeatDict = [...new Set(dict)];
  if (noRepeatDict.length > 0) {
    script += `'${noRepeatDict.join("','")}'`;
  } else {
    script += ``;
  }
  return script;
};

// 获取类型
const getValueType = (column: GenTableColumnEntity) => {
  // 控件枚举
  const obj = {
    input: 'input',
    textarea: 'textarea',
    select: 'select',
    radio: 'radio',
    checkbox: 'checkbox',
    datetime: 'date-picker',
    'input-number': 'input-number',
  };
  const val = obj[column.htmlType];
  if (val) {
    return `valueType:'${val}',`;
  }
  return '';
};

// 获取类型对应关联属性
const getValueTypeAttr = (column: GenTableColumnEntity, hideInTable: boolean, hideInForm: boolean, hideInSearch: boolean) => {
  let htmlStr = '';
  if (column.isList === '1' && !hideInTable) {
    htmlStr += `tableColumnProps: {
              align: 'center'
          },
    `;
  }
  if (['select', 'checkbox', 'radio'].includes(column.htmlType) && column.dictType) {
    htmlStr += `options:dictRawData.${column.dictType},
          optionsMap:{},
        `;
  }
  if (column.htmlType === 'input' && column.isInsert === '1') {
    htmlStr += `fieldProps:{
            maxlength: 200,
            modelModifiers: { trim: true },
          },
        `;
  }
  if (column.htmlType === 'textarea' && column.isInsert === '1') {
    htmlStr += `fieldProps:{
            maxlength: 200,
            showWordLimit: true,
            modelModifiers: { trim: true },
            autosize: { minRows: 2, maxRows: 4 }
          },
        `;
  }
  if (column.htmlType === 'datetime') {
    htmlStr += `fieldProps:{
            type: 'date',
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
          },
        `;
  }
  if (!hideInForm) {
    htmlStr += `propInForm:{}`;
  }
  return htmlStr;
};

// 生成列信息
const generateColumnsData = (columns: GenTableColumnEntity[]) => {
  let str = `[`;
  columns
    .filter((item) => item.isList !== '0' || item.isInsert !== '0' || item.isEdit !== '0')
    .forEach((item) => {
      const hideInTable = item.isList === '0';
      const hideInForm = item.isInsert === '0' && item.isEdit === '0';
      const hideInSearch = item.isQuery === '0';
      str += `
      {
        label: '${item.columnComment}',
        prop: '${item.javaField}',
        hideInSearch:${hideInSearch},
        hideInTable:${hideInTable},
        hideInForm:${hideInForm},
        ${getValueType(item)}
        ${getValueTypeAttr(item, hideInTable, hideInForm, hideInSearch)}
      },`;
    });
  str += `
    {
      label: '操作',
      prop: 'action',
      minWidth: '120px',
      hideInSearch: true,
      hideInForm: true,
      tableColumnProps: {
        align: 'center',
        fixed: 'right'
      }
    }
  `;
  str += `]`;
  return str;
};

export function hookTemplate(options: any) {
  const { BusinessName, moduleName, functionName, businessName, primaryKey, columns } = options;

  const apiBusinessName = Lodash.upperFirst(BusinessName);
  const dictStr = indexScriptDict(columns);
  const columnsStr = generateColumnsData(Array.from(columns));

  return `
    import { generateColumns, generateDictData } from '@/utils/plusUtil.js'
    import { list${apiBusinessName}Api, get${apiBusinessName}Api,add${apiBusinessName}Api,update${apiBusinessName}Api, del${apiBusinessName}Api, } from "@/api/${moduleName}/${businessName}";
    
    export const useCommonConfig = ()=>{
    
      // 基础配置
      const { proxy } = getCurrentInstance()
      const primaryKey = '${primaryKey}'
      const moduleName =  '${functionName}'
      const apiFn = {
        listApiFn: list${apiBusinessName}Api,
        delApiFn: del${apiBusinessName}Api,
        apiFnConfig:{
          info: get${apiBusinessName}Api,
          add:  add${apiBusinessName}Api,
          edit: update${apiBusinessName}Api
        }
      }
    
      // 删除前处理
      const beforeDelFn = (data)=>{
        return Array.isArray(data) ? data.map((item) => item[primaryKey]).join([',']) : data[primaryKey]
      }
    
      return {
        proxy,
        primaryKey,
        moduleName,
        apiFn,
        beforeDelFn,
      }
    
    }
    
    
    /**
     * 获取列和字典
     * @param isForm
     * @param data  表单数据对象
     */
    export const useColumnsDict = (isForm = false, data) => {
      const { proxy } = getCurrentInstance()
      let formData = ref({})
      if (isForm) {
        if (!data || !isRef(data)) {
          console.error('当 isForm 为 true 时，data 必须是一个 ref 对象')
          return
        }
        formData = data
      }
    
      const dictRawData  = proxy.useDict(...[
        ${dictStr}
      ])
    
      // 拓展了propInTable，propInForm
      // 定义在这个里面可以对外层进行覆盖(根据是列表还是表单)
      // orderInForm 可以调整在表单里面显示顺序
      const columnsData = ${columnsStr}
     
      const columns = ref([])
      columns.value = generateColumns(columnsData, isForm)
      const dictData = computed(()=>generateDictData(dictRawData))
      return {
        dictData,
        columns,
      }
    }
  `;
}
